#include<iostream>

#include<stdio.h>

#include<string>

#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include<unistd.h>

#include<string.h>

#include<unordered_map>

#define SIZE 1024

std::string defaultip = "0.0.0.0";
uint16_t defaultport = 8080;

enum
{
    SOCKETERR = 1,
    BINDERR
};

class udpserver
{
public:
    udpserver(const std::string& ip = defaultip, uint16_t port = defaultport):
        _ip(defaultip),
        _port(port),
        _sockfd(0),
        _isrunning(false)
    {
    }

    void init()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            perror("socket");
            exit(SOCKETERR);
        }

        sockaddr_in in;
        bzero(&in, sizeof(in));
        in.sin_addr.s_addr = inet_addr(_ip.c_str());
        in.sin_family = AF_INET;
        in.sin_port = htons(_port);
        if(bind(_sockfd, (sockaddr *)&in, sizeof(in)) < 0)
        {
            perror("bind");
            exit(BINDERR);
        }
        std::cout << "bind success" << std::endl;
    }

    void Broadcast(const char arr[], std::string ip, uint16_t clientport)
    {
        std::string message;
        message += '[';
        message += ip;
        message += ']';
        message += arr;

        for(auto& e : _um)
        {
            if(sendto(_sockfd, message.c_str(), message.size(), 0, (sockaddr*)&(e.second), sizeof(e.second)) < 0)
            {
                perror("sendto");
            }
        }
    }

    void check_port(sockaddr_in* in, const std::string& ip)
    {
        if(_um.count(ip) == 0)
        {
            _um[ip] = *in;
            std::cout << "add a new user：" << ip << std::endl;
        }
    }

    void run()
    {
        _isrunning = true;
        char buffer[SIZE] = {0};
        while(_isrunning)
        {
            sockaddr_in get;
            socklen_t g_len = sizeof(get);
            ssize_t ret = recvfrom(_sockfd, (void*)buffer, SIZE, 0, (sockaddr*)&get, &g_len);

            if(ret < 0)
            {
                perror("recvfrom");
                continue;
            }

            std::string strid = inet_ntoa(get.sin_addr);
            int intport = get.sin_port;
            strid += ":" + std::to_string(intport);

            check_port(&get, strid);

            buffer[ret] = 0;
            
            // if(sendto(_sockfd, (void*)buffer, ret, 0, (sockaddr*)&get, g_len) < 0)
            // {
            //     perror("sendto");
            // }

            Broadcast(buffer, strid, get.sin_port);
        }
    }

    ~udpserver()
    {
        close(_sockfd);
    }
private:
    std::string _ip;
    uint16_t _port;
    int _sockfd;
    bool _isrunning;
    std::unordered_map<std::string, sockaddr_in> _um;
};